<template>
	<section class="vbox">
		<section class="scrollable wrapper-md">
			<div class="row">
				<div class="col-sm-9">
					<div v-show="model.videoUrlType === 'src'" id="videoDiv"></div>
					<!-- <video id="myVideo" class="video-js" controls preload="auto" poster=""></video> -->

					<iframe v-if="model.videoUrlType === 'iFrame'" id="videoFrame" :src="playUrl" scrolling="no" border="0"
					 frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>

					<div class="wrapper-lg panel">
						<span class="h3 text-black font-thin "> {{ model.title }} </span>
						<span class="m-l-md">{{ model.author }}</span>
						<!-- <span class="m-l-md">{{ model.updateTime }}</span> -->
						<span class="pull-right">
							<span :class="{'favor m-r-md': true, 'active': favors.view != null}"><i class="fa fa-eye"></i>
								浏览 {{ statistics.viewCount }}</span>
							<a href="javascript:void(0)" :class="{'favor m-r-md': true, 'active': favors.comment != null}"><i class="fa fa-comment-o"></i>
								评论 {{ statistics.commentCount }}</a>
							<el-popover placement="bottom" trigger="hover" style="display: table-cell">
								<span slot="reference">
									<a href="javascript:void(0)" :class="{'favor m-r-md': true, 'active': favors.share != null}"><i class="fa fa-share"></i>
										分享 {{ statistics.shareCount }}</a>
								</span>
							</el-popover>
							<a href="javascript:void(0)" :class="{'favor m-r-md': true, 'active': favors.collect != null}" @click="showBookmarkDialog()"><i
								 class="fa fa-star-o"></i>
								收藏 {{ statistics.collectCount }}</a>
							<a href="javascript:void(0)" :class="{'favor m-r-md': true, 'active': favors.like != null}" @click="doLike()"><i
								 class="fa fa-thumbs-o-up"></i> 赞 {{ statistics.likeCount }}</a>
						</span>
						<!-- <div class="line b-b"></div> -->
						<!-- <div class="post-sum" v-html="model.intr"></div> -->
					</div>
					<!-- <v-comment></v-comment> -->
				</div>
				<div class="col-sm-3 ">
					<div class="panel panel-default">
						<div class="panel-heading">列表</div>
						<div class="panel-body" style="overflow: auto; max-height: 760px;">
							<!-- 系列视频列表 -->
							<ul v-if="model.isSeries" style="line-height: 45px;">
								<li :class="activeIndex == index ? 'active m-sm':'m-sm'" v-for="(item,index) in videoItems" :key="index">
									<span class="cursor" @click="playItem(item);activeIndex=index">{{item.title}}</span>
								</li>
							</ul>
							<!-- 推荐列表 -->
							<div v-else class="" v-for="item in recommendedList">
								<div class="item col-sm-6 col-xs-6 m-b-sm">
									<div class="pos-rlt">
										<div class="top">
											<span class="badge bg-empty m-l-sm m-t-sm pull-right ">{{ item.author }}</span>
											<div class="text-warning padder m-t-sm text-sm">
												<i class="fa fa-star"></i>
												<i class="fa fa-star"></i>
												<i class="fa fa-star"></i>
												<i class="fa fa-star-o text-muted"></i>
												<i class="fa fa-star-o text-muted"></i>
											</div>
										</div>
										<div class="bottom m-b-sm pos-rlt">
											<span class="badge bg-empty m-l-xs m-t-sm text-md">{{ item.title }}</span>
										</div>
										<a href="javascript:void(0)" @click="play(item)">
											<img :src="$api.file.url.view + item.poster" alt="" class="r r-2x img-full center-block">
										</a>
									</div>
								</div>
							</div>

							<!-- 华藏弘法电台 -->
							<iframe v-if="model.title=='华藏弘法电台'" height="500px" width="100%" src="https://hk2.amtb.de/mycalendar/mycalendar_embed.php?calendar_name=education&amp;showview=day&amp;valign=true&amp;showtimecolumns=start">
							</iframe>

							<!-- <article class="media">
								<a href="#" class="pull-left thumb-lg m-t-xs">
									<img src="/static/images/m45.jpg">
								</a>
								<div class="media-body">
									<a href="#" class="font-semibold">满园春色</a>
									<div class="text-xs block m-t-xs"><a href="#">禅心</a> 1 周 前</div>
								</div>
							</article> -->
						</div>
					</div>
				</div>
			</div>
		</section>
		<btn-goback></btn-goback>

		<el-dialog title="添加到收藏夹" v-model:visible="bookmarkDialogVisible" :center="true" width="30%">
			<el-table size="medium" ref="multipleTable" :data="bookmarks" style="width: 100%" :show-header="false" :stripe="false"
			 @select="selectBookmark">
				<el-table-column prop="title" label="收藏夹"></el-table-column>
				<el-table-column type="selection" width="55"> </el-table-column>
			</el-table>
			<div class="m-t-md m-b-lg">
				<input type="text" class="form-control pull-left" v-model="newBookmarkTitle" style="width: 76%;" placeholder="输入收藏夹名称">
				<button type="button" class="btn btn-info pull-right" @click="addBookmark()">新建收藏夹</button>
			</div>
			<div slot="footer" class="dialog-footer">
				<div class="row">
					<div class="col-sm-6 col-xs-6"><button class="btn btn-light" style="width: 100%" @click="bookmarkDialogVisible = false">取
							消</button></div>
					<div class="col-sm-6 col-xs-6"><button class="btn btn-success" style="width: 100%" @click="doCollect()">确 定</button></div>
				</div>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	// videojs
	import videojs from 'video.js'
	import resolveUrl from '@videojs/vhs-utils/es/resolve-url';
	window.HELP_IMPROVE_VIDEOJS = false;
	var myPlayer;

	import vComment from '@/components/Comment'

	export default {
		name: 'video-detail',
		props: {

		},
		components: {
			// videoPlayer
			vComment
		},
		data() {
			return {
				userId: null,
				webSites: [],
				playUrl: '',
				model: {
					mediaType: 'audio',
					source: '1',
					createUser: '1',
					updateTime: '',
					publish: true,
					intr: '',
					content: '',
					commentCount: 0,
					viewsCount: 0,
					likeCount: 0
				},
				statistics: {
					"viewCount": 0,
					"commentCount": 0,
					"shareCount": 0,
					"collectCount": 0,
					"likeCount": 0,
				},
				favors: {
					"view": null,
					"comment": null,
					"share": null,
					"collect": null,
					"like": null
				},
				activeIndex: 0,
				videoItems: [],
				collectedBookmarkId: null, //数据库中已经收藏的收藏夹id
				collectedBookmarkItemId: null, //数据库中已经收藏的收藏项id
				selectedBookmark: null, //选中的收藏夹
				bookmarkDialogVisible: false, //收藏夹显隐
				newBookmarkTitle: null, //新建收藏夹名称
				bookmarks: [],
				recommendedList: []
			}
		},
		async mounted() {
			this.userId = this.$store.state.auth.userId;

			//初始化播放器,创建dom标签，解决播放器销毁后将myVideo元素一块销毁
			var myVideoDiv = document.getElementById("videoDiv")
			myVideoDiv.innerHTML = '<video id="myVideo" class="video-js" controls preload="auto" poster=""></video>';
			await this.initVideo();

			this.$api.sysDict.queryDictItems("website").then(data => {
				this.webSites = data;
			});

			//业务逻辑
			const params = this.$route.params;
			console.debug('params:', params);
			if (null != params.id) {
				this.$api.video.queryById(params.id).then(data => {
					this.model = data;
					this.playUrl = data.url;
					document.title = this.model.title + ' | ' + document.title;
					if (this.model.isSeries) {
						this.queryVideoItems(); //集
					} else {
						this.play(this.model);
					}
				});

				this.$api.mediaStatistics.queryById(params.id).then(data => {
					console.debug('mediaStatistics.data', data)
					if (data.id != null)
						this.statistics = data;
				});

				this.$api.userMediaFavor.getUserFavorsForOneMedia(this.userId, params.id).then(data => {
					this.favors = data;
				});

				this.$api.video.recommendedList(params.id).then(data => {
					this.recommendedList = data;
				});

			}
			// 			VideoPlayer.setMedia({
			// 				title: "新喜剧之王-疾风少女",
			// 				webmv: "http://qukufile2.qianqian.com/data2/video/196a34ae006e7eeda1d8b9827c70f96b/611883164/611883164.mp4",
			// 				poster: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548486934&di=d92cb09a361749edbf65e25ab2f5d11f&imgtype=jpg&er=1&src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F7316423340%2F1000"
			// 			});
		},
		methods: { //设置当前播放视频
			initVideo() {
				myPlayer = videojs('myVideo', {
						bigPlayButton: false,
						textTrackDisplay: true,
						posterImage: true,
						errorDisplay: true,
						controlBar: true,
						html5: {
							vhs: {
								overrideNative: true,
								withCredentials: false
							}
						}
					},
					function() {
						// this.play();
					}
				)
			},
			play(video) {
				myPlayer.src([{
					//type: "application/x-mpegURL",
					cacheEncryptionKeys: true,
					src: video.url
				}]);
				myPlayer.play();
				window.scrollTo(0, 0);
			},
			queryVideoItems() {
				this.$api.videoItem.list({
					videoId: this.model.id
				}).then(data => {
					this.videoItems = data;
				});
			},
			async playItem(videoItem) {
				await this.$api.videoItem.queryById(videoItem.id).then(data => {
					if (videoItem.videoUrlType === 'iFrame') {
						this.playUrl = videoItem.url;
					} else {
						videoItem.url = data.url;
						this.play(videoItem); //源地址播放
					}
				});
			},
			doLike() {
				/**
				 * 未点赞则保存，再点删除赞
				 */
				if (this.favors.like == null) {
					this.$api.userMediaFavor.add({
						mediaId: this.model.id,
						favor: 'LIKE'
					}).then(data => {
						this.favors.like = data;
						this.statistics.likeCount += 1;
					});
				} else {
					this.$api.userMediaFavor.delete(this.favors.like).then(data => {
						this.favors.like = null;
						this.statistics.likeCount -= 1;
					});
				}
			},
			showBookmarkDialog() {
				/**
				 * 加载收藏夹列表
				 */
				this.$api.bookmark.list({
					userId: this.userId
				}).then(data => {
					this.bookmarks = data;
					this.bookmarkDialogVisible = true;
					/**
					 * 已收藏，查询收藏夹的id，并选中table中的行
					 */
					if (this.favors.collect != null) {
						this.$api.bookmarkItem.list({
							userId: this.userId,
							mediaId: this.model.id
						}).then(data => {
							if (data.length != 0) {
								this.collectedBookmarkItemId = data[0].id;
								this.collectedBookmarkId = data[0].bookmarkId;
								let index = this.bookmarks.findIndex(item => item.id == this.collectedBookmarkId);
								this.$refs.multipleTable.toggleRowSelection(this.bookmarks[index]);
							}
						});
					}
				});
			},
			//选择收藏夹
			selectBookmark(selection, row) {
				if (selection.length != 0) {
					this.selectedBookmark = row;
					this.$refs.multipleTable.clearSelection();
					this.$refs.multipleTable.toggleRowSelection(row);
				} else { //取消选中
					this.selectedBookmark = null;
				}
			},
			doCollect() {
				/**
				 * 选中 && （未收藏 或 修改收藏夹） -> 保存
				 */
				if (this.selectedBookmark != null && this.selectedBookmark.id != this.collectedBookmarkId) {
					this.$api.bookmarkItem.add({
						bookmarkId: this.selectedBookmark.id,
						mediaId: this.model.id
					}).then(data => {
						this.favors.collect = true;
						this.statistics.collectCount += 1;
					});
				}
				/**
				 *  取消收藏 或 修改收藏夹 -> 删除已收藏的关联关系
				 */
				if (this.collectedBookmarkId != null && (this.selectedBookmark == null || this.selectedBookmark.id != this.collectedBookmarkId)) {
					this.$api.bookmarkItem.delete(this.collectedBookmarkItemId).then(data => {
						this.favors.collect = null;
						this.statistics.collectCount -= 1;
					});
				}
				this.bookmarkDialogVisible = false;
				this.selectedBookmark = null;
				this.collectedBookmarkId = null;
				this.collectedBookmarkItemId = null;
			},
			//新建收藏夹
			addBookmark() {
				if (this.newBookmarkTitle == null) return;
				this.$api.bookmark.add({
					userId: this.userId,
					title: this.newBookmarkTitle
				}).then(data => {
					this.newBookmarkTitle = null;
					this.showBookmarkDialog();
				});
			}
		},
		filters: {
			filterSysDict(key, data) {
				console.debug('filter key:', key);
				var name = "其他";
				console.debug('data:', data);
				for (let i = 0; i < data.length; i++) {
					console.debug('data[i].code:', data[i].code);
					if (data[i].code == key) {
						name = data[i].name;
						console.debug('name:', name);
						break;
					}
				}
				console.debug('filter name:', name);
				return name;
			}
		},
		//组件销毁
		unmounted() { // beforeUnmount unmounted
			myPlayer.dispose()
		}
	}
</script>

<style>
	@import url("~video.js/dist/video-js.min.css");
	

	@media screen and (min-width: 992px) {
		#myVideo {
			width: auto;
			min-height: 580px;
			max-height: 750px;
		}

		#videoFrame {
			width: 100%;
			height: 750px;
			background-color: black;
		}
	}

	@media (max-width: 767px) {
		#myVideo {
			width: auto;
			height: auto;
			min-height: 300px;
		}

		#videoFrame {
			width: 100%;
			height: 300px;
			background-color: black;
		}
	}



	.active {
		color: #1e82d2;
		border-color: #409EFF;
	}

	/**
	 * 用户喜好点击变色
	 */
	.favor {
		display: table-cell;
		width: 80px;
		line-height: 30px;
	}

	.favor.active {
		color: #1ab667;
	}

	.favor:not(.active) i {
		color: #ccc;
	}

	a.favor:hover,
	a.favor:focus {
		font-size: 1.2em;
	}

	.el-table .cell {
		line-height: 40px;
	}

	.el-table .cell:hover {
		cursor: pointer;
	}

	/**
	 * 隐藏bilibili吐槽div
	 */
	.bilibili-player-video-sendjumpbar {
		display: none !important;
	}
</style>

<style scoped="scoped">
	.el-dialog {
		width: 450px !important;
	}

	/**
	 * 解決video播放器自动高度
	 */
	@media (max-width:768px) {
		#myVideo {
			min-height: auto;
		}
	}

	#myVideo {
		max-height: 800px;
	}

	.video-js.vjs-fill,
	.video-js .vjs-tech {
		height: auto !important;
		max-height: 800px;
	}

	.video-js .vjs-tech {
		position: inherit;
	}

	.myVideo-dimensions {
		height: auto;
	}

	/**
	 * 解決video end
	 */
</style>
